package com.nwpu.am.controller.admin;

import com.nwpu.am.constant.ErrorConstant;
import com.nwpu.am.pojo.dto.KnowledgeDTO;
import com.nwpu.am.pojo.entity.Knowledge;
import com.nwpu.am.pojo.entity.Rule;
import com.nwpu.am.result.Result;
import com.nwpu.am.service.KnowledgeService;
import com.nwpu.am.service.RuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * KnowledgeController
 *
 * @author Fbf
 * @version 1.0
 * {@code @date} 2024/6/5
 */

@RestController
@RequestMapping("/knowledge")
@Slf4j
@Api(tags = "知识库接口")
public class KnowledgeController {

    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private RuleService ruleService;

    @PostMapping("/selectAll")
    @ApiOperation("展示知识库")
    @RequiresPermissions("admin:knowledge:select")
    public List<Knowledge> display() {
        return knowledgeService.getAllKnowledge();
    }

    @PostMapping("/add")
    @ApiOperation("添加知识")
    @RequiresPermissions("admin:knowledge:add")
    public Result<String> add(@RequestBody @Validated KnowledgeDTO knowledgeDTO) {
        return knowledgeService.addKnowledge(knowledgeDTO) == 1 ?
                Result.success() :
                Result.error(ErrorConstant.ADD_WRONG);
    }

    @DeleteMapping("/delete/{knowledgeId}")
    @ApiOperation("删除知识")
    @RequiresPermissions("admin:knowledge:delete")
    public Result<String> deleteById(@PathVariable("knowledgeId") long knowledgeId) {
        int ret = knowledgeService.deleteKnowledge(knowledgeId);
        ArrayList<Rule> rules = ruleService.getAllRule();
        for (Rule r : rules) {
            if (r.getPremiseKnowledgeId() == knowledgeId || r.getConclusionKnowledgeId() == knowledgeId) {
                ruleService.deleteRule(r.getRuleId());
            }
        }
        return ret == 1 ?
                Result.success() :
                Result.error(ErrorConstant.DELETE_WRONG);
    }

    @PostMapping("/select/{knowledgeId}")
    @ApiOperation("查找知识")
    @RequiresPermissions("admin:knowledge:select")
    public Knowledge selectById(@PathVariable("knowledgeId") long knowledgeId) {
        return knowledgeService.selectById(knowledgeId);
    }
}
